<script setup lang="ts">
import {
  LexicalComposer,
  LexicalPlainTextPlugin,
  LexicalHistoryPlugin,
  LexicalContentEditable
} from 'lexical-vue'
import { $getRoot, $createParagraphNode, $createTextNode } from 'lexical'
import VariableBlockPlugin from '@/views/LLMStudio/build/components/prompt-editor/variable-block/index.vue'
import { VariableNode } from '@/views/LLMStudio/build/components/prompt-editor/variable-block/node'
import CustomErrorBoundary from '@/views/LLMStudio/build/components/prompt-editor/CustomErrorBoundary.vue'

// height
const props = defineProps({
  height: {
    type: Number,
    default: 250
  }
})

const exampleTheme = {
  ltr: 'ltr',
  rtl: 'rtl',
  placeholder: 'editor-placeholder',
  paragraph: 'editor-paragraph'
}

const editorConfig = {
  theme: exampleTheme,
  editable: true,
  onError(error: Error) {
    console.error(error)
  },
  nodes: [VariableNode],
  editorState: () => {
    const root = $getRoot()
    if (root.getFirstChild() === null) {
      const paragraph = $createParagraphNode()
      paragraph.append($createTextNode(''))
      root.append(paragraph)
    }
  }
}
</script>

<template>
  <LexicalComposer :initial-config="editorConfig">
    <CustomErrorBoundary>
      <div class="editor-container">
        <LexicalPlainTextPlugin>
          <template #contentEditable>
            <LexicalContentEditable
              class="editor-input"
              :style="{
                'min-height': `${props.height}px`
              }"
            />
          </template>
          <template #placeholder>
            <div class="editor-placeholder">
              在这里写你的提示词，输入'{' 插入变量、输入'/' 插入提示内容块
            </div>
          </template>
        </LexicalPlainTextPlugin>
        <LexicalHistoryPlugin />
        <VariableBlockPlugin />
      </div>
    </CustomErrorBoundary>
  </LexicalComposer>
</template>
<style lang="scss">
.editor-container {
  background: #fff;
  border-radius: 2px;
  color: #000;
  position: relative;
  line-height: 20px;
  font-weight: 400;
  text-align: left;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}

.editor-input {
  padding: 10px 10px;
  resize: none;
  font-size: 15px;
  caret-color: rgb(5, 5, 5);
  position: relative;
  tab-size: 1;
  outline: 0;
  caret-color: #444;
}

.editor-placeholder {
  color: #999;
  overflow: hidden;
  position: absolute;
  text-overflow: ellipsis;
  top: 10px;
  left: 10px;
  font-size: 13px;
  user-select: none;
  display: inline-block;
  pointer-events: none;
}

.editor-paragraph {
  margin: 0 0 15px 0;
  position: relative;
}
</style>
